package week2nd;

import java.util.Scanner;
import java.util.Stack;

public class PostfixEvaluator {
    private final static char ADD = '+';
    private final static char SUB = '-';
    private final static char MUL = '*';
    private final static char DIV = '/';

    private LinkedStack<Integer> linkedStack;

    public PostfixEvaluator() {
        linkedStack = new LinkedStack<Integer>();
    }

    public int evaluate(String expression) {

        int op1, op2, result = 0;

        String token;
        Scanner parser = new Scanner(expression);

        while (parser.hasNext()) {
            token = parser.next();

            //System.out.println(token);
            if (isOperator(token)) {
                op2 = (linkedStack.pop()).intValue();
                op1 = (linkedStack.pop()).intValue();
                result = evaluateSingleOperator(token.charAt(0), op1, op2);
                linkedStack.push(new Integer(result));

            } else {
                linkedStack.push(new Integer(Integer.valueOf(token)));
            }
        }

        return result;
    }

    private int evaluateSingleOperator(char operation, int op1, int op2) {

        int result = 0;
        switch (operation) {
            case ADD:
                result = op1 + op2;
                break;
            case SUB:
                result = op1 - op2;
                break;
            case MUL:
                result = op1 * op2;
                break;
            case DIV:
                result = op1 / op2;
                break;

        }

        return result;
    }

    /**
     * 判断是否是运算符
     *
     * @param token
     * @return
     */
    private boolean isOperator(String token) {
        return (token.equals("+") || token.equals("-") || token.equals("*") || token
                .equals("/"));
    }

}